from invidious import PlaylistItem

from src.vobjects.video import Video
from src.vobjects.item import Item

from src.config import Config

import os

class Playlist(PlaylistItem):

    def to_item(self):
        title = self.title
        fstr = f"{self.videoCount} videos"
        sstr = self.author

        status = {
            "url" : f"playlist?list={self.playlistId}"
        }

        return Item(title, fstr, sstr, "", self, "[>]", status=status)

    def from_json(self, jsn):
        self.title      = jsn['title']
        self.videos     = jsn['videos']
        self.url        = jsn['url']

        videos = []
        for videojs in self.videos:
            video = Video()
            video.from_json(videojs)
            videos.append(video)
        self.videos = videos

        return self

    def play(self, play_option: str="", mirror: str=""):
        config = Config()

        link = mirror + "/playlist?list=" + self.playlistId

        command = "mpv "
        if play_option == "V": command += "--aid=0 "
        elif play_option == "A": command += "--vid=0 "
        command += f"--ytdl-format='bestvideo[height<={config.StandartVideoQuality}]+bestaudio/best' "
        
        if not config.WaitForVideoEnd: command += "--no-terminal "
        command += link
        if not config.WaitForVideoEnd: command += " &"

        print(command)

        os.system(command)




